﻿var CONTEXT_PATH = "http://" + document.location.host;
var fillColor = "000000"; //鼠标上移颜色
var fillOpacity = 0.5;
var selectColor = "ffff00"; //选择颜色
var selectOpacity = 0.5;
//var submitColor = "e91d26"; //自己预定的车位颜色
var submitColor = "FF0000"; //自己预定的车位颜色
var submitOpacity = 0.5;
var othersColor = "FF0000"; //别人预定的车位颜色
var othersOpacity = 0.5;
var othersOpacity = 0.5;
var guideColor = "FF6600"; //引导销控
var guideOpacity = 0.8;
var guideROpacity = 0.5;
var orderColor = "FFFF00"; //后台预定
var orderOpacity = 0.5;
var redColor = "FF0099"; //后台预定翻红
var redOpacity = 0.8;
var redROpacity = 0.5;
var greenColor = "0000fe"; //准备颜色
var greenOpacity = 0.5;
var carData = null; //车位数据
var timeoutstamp = 5 * 60 * 1000;
//车位购物车
var carShopList = [];
var carloadend = false;
var annarr = [];

function CarInit(initData) {
    var config = JSON.parse(initData.Config);//配置
    CarConfig(config);
    var carlist = JSON.parse(initData.CarList);//房间数据
    ShowCarGrid(carlist);
    var shoplist = JSON.parse(initData.ShopList);//购物车
    if (typeof (window.SetCarShopCart) === "function") {
        window.SetCarShopCart(shoplist);
    }
}

var longdowncount;//项目长时间倒计时时间
var shortdowncount;//项目短时间倒计时时间
//0,1、未开始，2、预览，3、抢购倒计时，4、抢购中，5、结束，6、结束，页面弹出
var timearr = [0, 0, 0, 0, 0, 0, 0];
function CarConfig(option) {
    if (window.ismonitor) return;
    timeoutstamp = option.ExpiredTime;//过期时间
    timearr[2] = option.PreviewTime;//预览时间戳
    timearr[3] = option.CountDownTime;//抢购倒计时
    timearr[4] = option.ShoppingTime;//抢购总时间戳
    window.cartmaxcount = option.ShoppingCartUpper * window.formcount;//购物车最大数量 * 客户筹数


    longdowncount = option.StateTime; //项目长时间倒计时时间
    var remainingtime = option.RemainingTime;//到下一步剩余时间
    var pagestate = parseInt(option.State); // 项目当前状态
    if (remainingtime !== 0) {
        //剩余时间不为0，修改下一步时间
        timearr[pagestate] = remainingtime;
    }
    window.ShowPageState(pagestate);
}

function timeout() {
    $("#outdiv").remove();
    $(".cover_bg").hide();
}
function CarAnner(data) {
    annarr = [];
    for (var i in data) {
        if (data.hasOwnProperty(i)) {
            var ann = data[i];
            annarr.push(ann);
        }
    }
    SplaceAnner();
    if (annertime !== null) {
        clearInterval(annertime);
    }
    AnnerRun();
}

function SplaceAnner() {
    $("#ann .notice_active li").remove();
    for (var i in annarr) {
        if (annarr.hasOwnProperty(i)) {
            var ann = annarr[i];
            var li = $("<li class=\"notice_active_ch\"></li>");
            li.append("<span>" + ann.D_Title + "</span>");
            var date = ann.D_OperDate.substring(0, 11);
            li.append("<em>" + date + "</em>");
            $("#ann ul").append(li);
        }
    }
}

var annertime = null;
function AnnerRun() {
    var num = $('#ann .notice_active').find('li').length;
    if (num > 1) {
        annertime = setInterval('ShowAnner("#ann .notice_active")', 3500);
    }
}

function ShowAnner(obj) {
    $(obj)
        .find('ul')
        .animate({
            marginTop: "-3.6rem"
        },
            500,
            function () {
                $(this).css({ marginTop: "1px" }).find("li:first").appendTo(this);
            });

}
//构建区域
function buildArea(areaData) {
    $(".big_btn_div").empty();
    for (var a in areaData) {
        if (areaData.hasOwnProperty(a)) {
            var area = areaData[a];
            var div =
                $("<div class='button button-small button-rounded' style='margin-left:10px; margin-top:10px;' onclick='areaSelect(\"" +
                    area.ID +
                    "\")' id='area_" +
                    area.ID +
                    "' imgPath='" +
                    area.ImagePath +
                    "' name='" +
                    area.NAME +
                    "'>" +
                    area.NAME +
                    "</div>");
            $(".big_btn_div").append(div);
        }
    }
};

var areafirstload = true;
//选择区域
var imgContextPath = "http://" + document.location.host;
var areaSelect = function(areaId) {
    window.cleanGlobleData();
    var area = $("#area_" + areaId);
    var areaname = area.attr("name");
    var imgPath = area.attr("imgPath");
    var src = imgContextPath + imgPath;
    $(".big_btn_div div").removeClass("button-caution");

    var loagproxy = loadImgProxy();
    loagproxy($("#spaceImg"), src);

    $("#spaceImg").load(function () {
        area.addClass("button-caution");
        //页面初次加载获取数据
        if (!carloadend) {
            getCarData(window.user);
            var inter = setInterval(function () {
                if (carloadend) {
                    showlist(areaname);
                    clearInterval(inter);
                }
            }, 200);
        }else{
            showlist(areaname);
        }
    });
    if (!areafirstload) {
        //车位区域切换事件
        var json = window.wsorder.areachange(window.user, areaname);
        window.websocket.send(JSON.stringify(json));
    }
    areafirstload = false;
};

function loadImgProxy() {
    var imgCache = new Image();
    var dfd = $.Deferred();

    //加载完成事件处理，加载完成后进行resolve操作
    imgCache.onload = function () {
        dfd.resolve(this.src);
        window.hidePageWaiting();

    }
        return function(eleImg, src) {
            dfd.done(function () {
                //加载完成后，往图片元素上设置图片
                loadImg(eleImg, src);
            });

            window.showPageWaiting();
            imgCache.src = src;
            return dfd.promise();
        }
}

function loadImg(img, src) {
    img.attr("src", src);
}

var showlist  = function(areaname) {
    var arealist = [];
    for (var i in carData) {
        if (carData.hasOwnProperty(i)) {
            var cars = carData[i];
            if (cars.Area === areaname) {
                arealist.push(cars);
            }
        }
    }
    buildMap(arealist);
}
//构建地图热区
var buildMap = function (data) {
    var positionData = data;
    $("#spaceMapA").empty();
    $("canvas").remove();
    $(".map")
        .maphilight({
            "alwaysOn": false
        });
    for (var p in positionData) {
        if (positionData.hasOwnProperty(p)) {
            var d = positionData[p];
            var coords = d.x1 +
                "," +
                d.y1 +
                "," +
                d.x2 +
                "," +
                d.y2 +
                "," +
                d.x4 +
                "," +
                d.y4 +
                "," +
                d.x3 +
                "," +
                d.y3;
            var html = "<area shape=\"poly\" data='" +
                JSON.stringify(d) +
                "' id=\"" +
                d.Id +
                "\" spaceNo=\"" +
                d.CarNo +
                "\" coords=\"" +
                coords +
                "\" style=\"cursor: pointer;background-color: #333;\" nohref=\"nohref\" hidefocus=\"true\" ondblclick=\"areaAction(this)\" onmousemove=\"areaMouseOver(this, event)\" onmouseout=\"areaMouseOut(this, event)\">";
            $("#spaceMapA").append(html);
            var state = d.D_ShoppingCartState;
            var operation = d.D_ShoppingOper;
            var id = d.CarNo;
            if (window.ismonitor) {
                var monitor = d.Monitor;
                if (window.MonitorType === 1) {
                    highlightOrderSpaceGui(operation, state, monitor, id);
                } else if (window.MonitorType === 2) {
                    highlightOrderSpaceMon(operation, state, monitor, id);
                }
            } else {
                highlightOrderSpace(operation, state, id);
            }
        }
    }
    window.showCarSeat();
};

//获取车位数据
var getCarData = function (operation) {
    var json = wsorder.getlist(operation);
    websocket.send(JSON.stringify(json));
}

//加载区域数据
function ShowCarGrid(data) {
    carData = [];
    for (var i in data) {
        if (data.hasOwnProperty(i)) {
            var car = data[i];
            var id = car.Id;
            carData[id] = car;
        }
    }
    carloadend = true;
}

function GetCar(id) {
    id = parseInt(id);
    return carData[id];
}

//车位批量变更
function CarUpdateBatch(data) {
    for (var i in data) {
        if (data.hasOwnProperty(i)) {
            var car = data[i];
            var state = parseInt(car.toString().substr(0, 1));
            var monitor = car.toString().substr(1, 1);
            var id = parseInt(car.toString().substr(2));
            var rdata = {
                D_ID: id,
                D_state: state,
                D_Monitor: monitor
            }
            CarUpdate(rdata);
        }
    }
}

//车位数据列新
function CarUpdate(data) {
    if (window.carloadend === undefined || !window.carloadend) {
        return;
    }
    var monitor = parseInt(data.D_Monitor); //车位监控
    var id = data.D_ID;
    var state = data.D_state; //车位状态
    UpdateCarDate(id, state, monitor); //更新车位数据

    var othercl = "";
    var opacity = 1;
    if (!window.ismonitor) {
        //非监控页面
        if (monitor === 4 || monitor === 5) {
            //引导销控准备,后台翻红预定准备
            othercl = greenColor;
            opacity = greenOpacity;
        } else if (monitor === 1 || monitor === 3) {
            //引导销控，后台预定翻红
            othercl = othersColor;
            opacity = othersOpacity;
        } else if (monitor === 2) {
            //客户页面，后台预定无反映
            othercl = "none";
        } else if (state === 1) {
            //预定中
            othercl = greenColor;
            opacity = greenOpacity;
        } else if (state === 2) {
            //提交预定
            othercl = othersColor;
            opacity = othersOpacity;
        } else if (state === 0) {
            othercl = "none";
        }
    } else {
        //监控页面
        if (monitor !== 0) {
            if (window.MonitorType === 1) {
                //房间监控页面
                if (monitor === 1) {
                    othercl = guideColor; //销控
                    opacity = guideOpacity;
                } else if (monitor === 4) {
                    othercl = guideColor; //销控准备
                    opacity = guideROpacity;
                } else if (monitor === 2) {
                    othercl = orderColor; //后台预定
                    opacity = orderOpacity;
                } else if (monitor === 3) {
                    othercl = redColor; //后台预定翻红
                    opacity = redOpacity;
                } else if (monitor === 5) {
                    othercl = redColor; //后台预定翻红准备
                    opacity = redROpacity;
                } else if (state === 0) {
                    othercl = "none";
                }
            } else if (window.MonitorType === 2) {
                //房间预留
                if (monitor === 2) {
                    othercl = orderColor; //后台预定
                    opacity = orderOpacity;
                } else if (monitor === 3) {
                    othercl = redColor; //后台预定翻红
                    opacity = redOpacity;
                } else if (monitor === 5) {
                    othercl = redColor; //后台预定翻红准备
                    opacity = redROpacity;
                } else {
                    othercl = othersColor;
                    opacity = othersOpacity;
                }
            }
        } else if (state === 1) {
            //预定中
            othercl = greenColor;
            opacity = greenOpacity;
        } else if (state === 2) {
            //提交预定
            othercl = othersColor;
            opacity = othersOpacity;
        } else if (state === 0) {
            othercl = "none";
        }
    }
    if (othercl === "none") {
        cleanHighlightColor($("#" + id), true);
    } else {
        highlightSelectSpace($("#" + id), othercl, opacity, true);
    }
}

function UpdateCarDate(id, state, monitor) {
    window.carData[id].D_state = state;
    window.carData[id].D_Monitor = monitor;
}

var spaceId;
var spaceNo;
//热区双击事件
var areaAction = function (me) {
    var self = $(me);
    spaceId = self.attr("id");
    spaceNo = self.attr("spaceNo");
    var data = carData[spaceId];
    var monitor = data.Monitor;
    var state = data.State;
    $("#spaceId").val(spaceId);
    $("#CarNo").val(spaceNo);
    $("#Varsion").val(data.Varsion);

    $(".area_grid #info_card_nod").html(data.CarNo);
    $(".area_grid #info_card_infod").html(data.CarInfo);
    $(".area_grid #info_totald").html(data.CarTotal);
    $(".area_grid #info_benefitd").html(data.CarBenefit);
    $(".area_grid #info_remarkd").html(data.Remark);
    $(".area_grid #info_defensed").html(data.Defense);
    $(".area_grid #info_aread").html(data.Area);
    $(".area_grid #info_versiond").html(data.Varsion);

    $(".lcarno").html(data.CarNo);
    $(".lcarinfo").html(data.CarInfo);
    $(".ltotal").html(data.CarTotal);
    $(".lbenefit").html(data.CarBenefit);
    $(".lremark").html(data.Remark);
    $(".ldefense").html(data.Defense);
    $(".larea").html(data.Area);
    $(".lversion").html(data.Varsion);

    $("#spaceNoText").val("车位号：" + spaceNo + "号");
    if (window.iscarmark) {
        //客户抢购页面
        window.layerindex = layer.load(2, { time: 10000 });
        ClientOrder(spaceId);
    } else if (window.MonitorType === 1) {
        //车位销控
        if (monitor === 0 && state === 0) {
            window.setOp("setguidetrim");
        } else if (monitor === 4) {
            $("#op").val("setOrder");
            $("#setguide").unbind("click");
            $("#setguide").click(function() {
                $('#setguide').unbind("click");
                window.setOp("setguide");
            });
            $(".cover_bg").show();
            $(".info_div").show();
        }
    } else if (window.MonitorType === 2) {
        //引导销控
        $("#setguide").unbind("click");
        $("#setguide").click(function () {
            $('#setguide').unbind("click");
            window.setOp("setguide");
        });
        $(".cover_bg").show();
        $(".info_div").show();
    }
//    else if (cartIndex !== -1) {
//        cartCar(cartIndex, spaceId);
//    }
//    else if (index === -1) {
//        highlightSelectSpace(self, selectColor, selectOpacity, true);
//        var yu = window.ismonitor ? "后台预约" : "提交";
//
//        if (window.ismonitor) {
//            //后台预约
//            $("#op").val("setOrder");
//            //$("#submitOrder").css("display", "block");
//            $("#submitOrder").unbind("click");
//            $("#submitOrder").click(function () {
//                $('#submitOrder').unbind("click");
//                window.setOp("setorder");
//            });
//            //引导销控
//            $("#setguide").unbind("click");
//            $("#setguide").click(function () {
//                $('#setguide').unbind("click");
//                window.setOp("setguide");
//            });
//        } else {
//            //车位销售
//            $("#op").val("seat");
//            window.layerindex = layer.load(2, { time: 10000 });
//            submitOrder();
//            return;
//        }
//        $("#submitOrder").find("a").html(yu);
//        lockSpaceId = spaceId;
//    } else {
//        var un = window.ismonitor ? "取消后台预约" : "取消预约";
//        $("#submitOrder").find("a").html(un);
//        if (window.ismonitor) {
//            if (data.Monitor === 3) {
//                //$("#setcarunred").css("display", "block");
//                $("#setcarunred").unbind("click");
//                $("#setcarunred").click(function () {
//                    $('#setcarunred').unbind("click");
//                    window.setOp("setcarunred");
//                });
//            } else if (data.Monitor === 2) {
//                $("#submitUnOrder").unbind("click");
//                $("#submitUnOrder").click(function () {
//                    $('#submitUnOrder').unbind("click");
//                    window.setOp("unorder");
//                });
//                $("#setcarred").css("display", "block");
//                $("#setcarred").unbind("click");
//                $("#setcarred").click(function () {
//                    $('#setcarred').unbind("click");
//                    window.setOp("setcarred");
//                });
//            } else if (data.Monitor === 1)
//            {
//                $("#setunguide").unbind("click");
//                $("#setunguide").click(function () {
//                    $('#setunguide').unbind("click");
//                    window.setOp("setunguide");
//                });
//            }
//        } else {
//            $("#op").val("unseat");
//        }
//
//    }
//    $(".cover_bg").show();
//    $(".info_div").show();
};

//客户预定
function ClientOrder(spaceId) {
    var hasorder = false;
    for (var i in carShopList) {
        if (carShopList.hasOwnProperty(i)) {
            var cart = carShopList[i];
            var car = GetCar(spaceId);
            var state = parseInt(car.D_state);
            if (cart.state === 1 && cart.id.toString() === car.Id.toString()) {
                hasorder = true;
                showOrderInfo(spaceId);
            } else if (cart.state === 1 && state === 0) {
                hasorder = true;
                layer.confirm('<span style="font-size:16px;">您有预定的车位未处理，是否放弃并预定当前车位？</span>',
                    {
                        title: ["温馨提示", "font-size:18px; color:red; text-align:center;"],
                        btn: ['是', '否'], //按钮
                        btnAlign: 'c'
                    },
                    function(index) {
                        $("#op").val("seat");
                        submitOrder(); //直接提交车位预定
                        layer.close(index);
                        window.layerindex = layer.msg('车位预定中',
                            {
                                icon: 16,
                                shade: 0.01
                            });
                    });
            } else {
                closelayer();
            }
        }
    }
    if (!hasorder) {
        $("#op").val("seat");
        submitOrder(); //直接提交车位预定
    }
}

function showOrderInfo(id) {
    $(".cover_bg").show();
    $(".info_div").show();
    var index = getIndexByRoomCart(id);
    showTimeCountDown(index);
    //提交预定
    $("#submitOrder")
        .unbind("click")
        .bind("click",
        function () {
            UpdateShopCart(parseInt($("#spaceId").val()), 1, $("#name").val(), window.user, $("#cardno").val(), $("#tel").val());
            });
    //取消预定
    $("#calcleOrder")
        .unbind("click")
        .bind("click",
        function () {
                UpdateShopCart(parseInt($("#spaceId").val()), 2, $("#name").val(), window.user, $("#cardno").val(), $("#tel").val());
            });
}


function cartCar(cartIndex, id) {
    var state = parseInt(carShopList[cartIndex].state);
    hideBtn(state);
    if (state > 1) {
        $("#cartCountdown" + cartIndex).html("车位" + shopstatearr[state] + "！");
    }
    showTimeCountDown(cartIndex);
}

function closelayer() {
    if (window.layerindex) {
        window.layer.close(window.layerindex);
    }
}

//鼠标上移
var areaMouseOver = function(me, event) {
    event = event || window.event;
    var x = event.clientX + 20;
    var y = event.clientY + 20;
    var h = document.body.offsetHeight - y - $(".area_info").height(); //
    if (h <= 0) {
        y = y - $(".area_info").height() - 60;
    }
    var w = document.body.offsetWidth - x - $(".area_info").width();
    if (w <= 0) {
        x = x - $(".area_info").width() - 60;
    }
    $(".area_info")
        .show()
        .css({
            top: y,
            left: x
        });
    var id = $(me).attr("id");
    var data = carData[id];
    $(".area_info #info_card_no").html(data.CarNo);
    $(".area_info #info_card_info").html(data.CarInfo);
    $(".area_info #info_total").html(data.CarTotal);
    $(".area_info #info_benefit").html(data.CarBenefit);
    $(".area_info #info_remark").html(data.Remark);
    $(".area_info #info_defense").html(data.Defense);
    $(".area_info #info_area").html(data.Area);
    $(".area_info #info_version").html(data.Varsion);
    $(".area_info #info_name").html(data.Name);
    $(".area_info #info_cardno").html(data.CardNo);
    $(".area_info #info_tel").html(data.Tel);
};
var areaMouseOut = function(me, event) {
    $(".area_info").hide();
};
var lockSpaceId;
//预约车位
var lockSpace = function (id, oper, shopid) {
    closelayer();//消息等待
    if (window.user === oper) {
        if (!window.ismonitor) {
            carShopList.push({
                shopid: shopid,
                id: id,
                state: 1,
                oper: oper,
                time: timeoutstamp
            });
            window.showCarSeat();
            showOrderInfo(id);
            window.shopcarcount++;
            $("#tip").html("还有" + (3 - window.shopcarcount) + "次选购机会");
        }
    }
};

var UpdateShopCart = function (id, type, name, operation, cardno, tel) {
    window.layerindex = layer.load(2, { time: 10000 });
    var json = "";
    var cartid = window.GetCarCartId(id);
    if (type === 1) {
        //房间购物车数据提交
        json = window.wsorder.cartsubmit(name, operation, cardno, tel, id, cartid);
    } else if (type === 2) {
        //房间购物车取消
        json = window.wsorder.unseat(name, operation, cardno, tel, id, cartid);
    }

    window.websocket.send(JSON.stringify(json));
}

//取消预约车位
var unlockSpace = function (id) {
    $("#carsetbutton").hide();
    $(".cover_bg").hide();
    if (!window.monitor) {
        UpdateCarState(id, 2);
        window.showCarSeat();
        //清空倒计时
        $("#carsetbutton tr[tid=" + id + "] td:eq(" + ($("#carsetbutton tr[tid=" + id + "] td").length - 2) + ")").html("0");
    }
    closeOrderWin(true);
};


//关闭预约窗口
var closeOrderWin = function(force) {
    lockSpaceId = "";
    if (window.ismonitor) {
        
    }
    $(".info_div").hide();
    $(".cover_bg").hide();
    var data = carData[spaceId];
    if (window.ismonitor) {
        var monitor = data.Monitor;
        if (window.MonitorType === 1) {
            highlightCarSpaceGui(spaceId, monitor);
        } else if (window.MonitorType === 2) {
            highlightCarSpaceMon(spaceId, monitor);
        }
    } else {
    }
    $("#Varsion").val(data.Varsion);
};

//高亮选中车位
var highlightSelectSpace = function(self, color, opacity, alwaysOn) {
    var data = self.mouseout().data("maphilight") || {};
    data.alwaysOn = !data.alwaysOn;
    data.alwaysOn = alwaysOn;
    data.fillColor = data.alwaysOn ? color : fillColor;
    data.fillOpacity = data.alwaysOn ? opacity : fillOpacity;
    self.data("maphilight", data).trigger("alwaysOn.maphilight");
};


//清除高亮，force=true强制清除
var cleanHighlightColor = function (self, force) {
    if (force) {
        var data = self.mouseout().data('maphilight') || {};
        data.alwaysOn = false;
        data.fillColor = fillColor;
        data.fillOpacity = fillOpacity;
        self.data('maphilight', data).trigger('alwaysOn.maphilight');
    }
};

//高亮预定车位
var highlightOrderSpace = function(operation, state, id) {
    if (window.user === operation) { //自己预定的车位 
        if (state !== 0) {
            highlightSelectSpace($("#" + id), submitColor, submitOpacity, true);
        }
    } else if (state === 1) { //被别人预定了
        highlightSelectSpace($("#" + id), othersColor, othersOpacity, true);
    }
};

//引导高亮车位
var highlightOrderSpaceGui = function (operation, state, monitor, id) {
    if (monitor === 1) {
        //引导销控
        highlightSelectSpace($("#" + id), guideColor, guideOpacity, true);
    } else if (monitor === 2) {
        //后台预定
        highlightSelectSpace($("#" + id), orderColor, orderOpacity, true);
    }else if (monitor === 3) {
        //后台预定翻红
        highlightSelectSpace($("#" + id), redColor, orderOpacity, true);
    } else if (state === 1) { //被锁定了
        highlightSelectSpace($("#" + id), othersColor, othersOpacity, true);
    } else if (user === operation) { //自己预定的车位 
        highlightSelectSpace($("#" + id), submitColor, submitOpacity, true);
    } else if (state === 2) { //被别人预定了
        highlightSelectSpace($("#" + id), othersColor, othersOpacity, true);
    }
};

//后台预约高亮车位
var highlightOrderSpaceMon = function (operation, state, monitor, id) {
    if (monitor === 1) {
        //引导销控
        highlightSelectSpace($("#" + id), othersColor, guideOpacity, true);
    } else if (monitor === 2) {
        //后台预定
        highlightSelectSpace($("#" + id), orderColor, orderOpacity, true);
    } else if (monitor === 3) {
        //后台预定翻红
        highlightSelectSpace($("#" + id), redColor, orderOpacity, true);
    } else if (state === 1) { //被锁定了
        highlightSelectSpace($("#" + id), othersColor, othersOpacity, true);
    } else if (user === operation) { //自己预定的车位 
        highlightSelectSpace($("#" + id), submitColor, submitOpacity, true);
    } else if (state === 2) { //被别人预定了
        highlightSelectSpace($("#" + id), othersColor, othersOpacity, true);
    }
};

var highlightCarSpaceGui = function (id, monitor) {
    if (monitor === 1) {
        //引导销控
        highlightSelectSpace($("#" + id), guideColor, guideOpacity, true);
    } else if (monitor === 2) {
        //后台预定
        highlightSelectSpace($("#" + id), orderColor, orderOpacity, true);

    } else if (monitor === 3) {
        //后台预定翻红
        highlightSelectSpace($("#" + id), redColor, orderOpacity, true);
    }
};

var highlightCarSpaceMon = function (id, monitor) {
    if (monitor === 1) {
        //引导销控
        highlightSelectSpace($("#" + id), submitColor, guideOpacity, true);
    } else if (monitor === 2) {
        //后台预定
        highlightSelectSpace($("#" + id), orderColor, orderOpacity, true);
    
    } else if (monitor === 3) {
        //后台预定翻红
        highlightSelectSpace($("#" + id), redColor, orderOpacity, true);
    }
};

//提交、取消预约
var submitOrder = function () {
    closeOrderWin(true);
    UpdateSeat($("#name").val(), window.user, $("#cardno").val(), $("#tel").val(), $("#spaceId").val());
};


function setOp(val) {
    $("#op").val(val);
    window.CarGuideAjax(val, username, window.user, parseInt($("#spaceId").val()));
}

//车位销控发送消息
function CarGuideAjax(action, name, operation, id) {
    var json = eval("window.wsorder." +
        action +
        "('" +
        name +
        "','" +
        operation +
        "'," +
        id +
        ")");
    window.websocket.send(JSON.stringify(json));
}
//预约，取消预约
var UpdateSeat = function (name, operation, cardno, tel, carno) {
    var json = "";
    var action = $("#op").val();
    if (action === "seat") {
        json = wsorder.seat(name, operation, cardno, tel, carno);
    } else if (action === "unseat") {
        json = wsorder.unseat(name, operation, cardno, tel, carno);
    }
    window.websocketsent(JSON.stringify(json));
};

//后台预定
var backOrderSpace = function (id) {
    if (!window.ismonitor) return;
    closeOrderWin(true);
    $("#CarNo").val();
    highlightSelectSpace($("#" + id), orderColor, orderOpacity, true);
}
//后台预定取消
var backUnOrderSpace = function (id) {
    if (!window.ismonitor) return;
    closeOrderWin(true);
    $("#CarNo").val();
    cleanHighlightColor($("#" + id), true);
}
//后台预定翻红
var carRedSpace = function (id, varsion, operation) {
    if (window.ismonitor) {
        closeOrderWin(true);
        $("#CarNo").val();
        highlightSelectSpace($("#" + id), redColor, orderOpacity, true);
    } else {
        window.lockSpace(id, varsion, operation);
    }
}
//后台预定取消翻红
var carUnRedSpace = function (id) {
    if (!window.ismonitor) return;
    closeOrderWin(true);
    $("#CarNo").val();
    cleanHighlightColor($("#" + id), true);
}

//引导销控
var GuideSpace = function (id) {
    if (!window.ismonitor) return;
    closeOrderWin(true);
    $("#CarNo").val();
    if(window.MonitorType==1)
        highlightSelectSpace($("#" + id), guideColor, guideOpacity, true);
    else 
        highlightSelectSpace($("#" + id), submitColor, guideOpacity, true);
}
//引导销控取消
var UnGuideSpace = function (id) {
    if (!window.ismonitor) return;
    closeOrderWin(true);
    $("#CarNo").val();
    cleanHighlightColor($("#" + id), true);
}

//取消操作
var cancelOrder = function() {
    closeOrderWin(true);
};

//更新购物车状态
function SetCarCartState(id, state) {
    for (var i in carShopList) {
        if (carShopList.hasOwnProperty(i)) {
            carShopList[i].state = state;
        }
    }
}

var closecarsetbutton = function () {
    $("#carsetbutton").hide();
    $(".cover_bg").hide();
}

var showPageWaiting = function() {
    $("body").append("<div id='waiting'></div>");
    showWaiting($("#waiting")[0]);
};
var hidePageWaiting = function() {
    $("#waiting").hide().remove();
};
var hideTipFlag = null;

//弹窗
var showTip = function(msg) {
    window.clearTimeout(hideTipFlag);
    $(".tip_content").html(msg);
    $(".tip_box")
        .stop()
        .animate({
                bottom: 0
            },
            700);
    hideTipFlag = window.setTimeout("hideTip()", 3000);
};

//隐藏弹窗
var hideTip = function() {
    $(".tip_box")
        .animate({
                bottom: "-140px"
            },
            400);
    $(".tip_content").html("");
};

//重置全局变量
var cleanGlobleData = function() {
    spaceId = "";
    lockSpaceId = "";
};


$(function() {
    //初始化计数器
    var num = 0;
    //区块锁定标识
    var lock = false;
    //加载layer拓展
    layer.config({
        extend: "extend/layer.ext.js"
    });
    //右键菜单参数
    context.init({
        fadeSpeed: 100,
        filter: function($obj) {
        },
        above: "auto",
        preventDoubleContext: true,
        compress: false
    });

    //创建拖拽方法
    $("#canvas")
        .mousedown(function(e) {
            var canvas = $(this);
            e.preventDefault();
            var pos = $(this).position();
            pos.left = $(this).css("marginLeft").replace("px", "");
            pos.top = $(this).css("marginTop").replace("px", "");
            this.posix = { 'x': e.pageX - pos.left, 'y': e.pageY - pos.top };

            $.extend(document,
            {
                'move': true,
                'move_target': this,
                'call_down': function(e, posix) {
                    var imgWidth = $("#spaceImg").width();
                    var imgHeight = $("#spaceImg").height();
                    var spaceDivWidth = $(".space_div").width();
                    var spaceDivHeight = $(".space_div").height();
                    var top = e.pageY - posix.y;
                    var left = e.pageX - posix.x;

                    if (spaceDivWidth > imgWidth) {
                        left = 0;
                    } else {
                        if (e.pageX - posix.x > 0) {
                            left = 0;
                        }
                        if (e.pageX - posix.x + imgWidth < spaceDivWidth - 20) {
                            left = spaceDivWidth - imgWidth - 20;
                        }
                    }
                    if (spaceDivHeight > imgHeight) {
                        top = 0;
                    } else {
                        if (e.pageY - posix.y > 0) {
                            top = 0;
                        }
                        if (e.pageY - posix.y + imgHeight < spaceDivHeight - 70) {
                            top = spaceDivHeight - imgHeight - 70;
                        }
                    }
                    canvas.css({
                        'cursor': "move",
                        'marginTop': top + "px",
                        'marginLeft': left + "px"
                        //                    'top': top,
                        //                    'left': left
                    });

                },
                'call_up': function() {
                    canvas.css("cursor", "default");
                }
            });
        })
        .on("mousedown",
            ".box",
            function(e) {
                if (lock) return;
                var pos = $(this).position();
                this.posix = { 'x': e.pageX - pos.left, 'y': e.pageY - pos.top };
                $.extend(document, { 'move': true, 'move_target': this });
                e.stopPropagation();
            })
        .on("mousedown",
            ".box .coor",
            function(e) {
                var $box = $(this).parent();
                var posix = {
                    'w': $box.width(),
                    'h': $box.height(),
                    'x': e.pageX,
                    'y': e.pageY
                };
                $.extend(document,
                {
                    'move': true,
                    'call_down': function(e) {
                        $box.css({
                            'width': Math.max(30, e.pageX - posix.x + posix.w),
                            'height': Math.max(30, e.pageY - posix.y + posix.h)
                        });
                    }
                });
                e.stopPropagation();
            });

});

//显示客户预定车位
var ShowSeat = function () {
    $(".cover_bg").show();
    var buttondivheight = parseInt($("#carsetbutton").css("height"));
    var buttondivwidth = parseInt($("#carsetbutton").css("width"));
    var top = (window.innerHeight - buttondivheight) / 2;
    var left = (window.innerWidth - buttondivwidth) / 2;
    $("#carsetbutton").css("top", top + "px").css("left", left + "px").show();
}


var loginout = function () {
    $.ajax({
        type: 'post', dataType: 'json',
        url: '../data/Tuser.ashx',
        data: [{ name: 'Action', value: 'logout' }],
        success: function (result) {
            javascript: location.replace("../rulecar.aspx");
            alert("您已退出登录");
        }
    });
}

function getUser() {
    $.ajax({
        url: "../data/Tuser.ashx?Action=GetOnline&rnd=" + Math.random(),
        type: 'get',
        success: function (result) {
            if (result == "false") {
                alert("您已退出登录");
                javascript: location.replace("../rulecar.aspx");
            }
        },
        error: function () {
            javascript: location.replace("../rulecar.aspx");
        }
    });
}

$(window).bind('unload', function () {
    delCookie("car_uid");
    $.ajax({
        url: "../data/Tuser.ashx",
        type: "post",
        data: [{ name: 'Action', value: 'logout' }],
        success: function () {
            alert("您已退出登录");
            javascript: location.replace("../rulecar.aspx");
        },
        error: function () {
            javascript: location.replace("../rulecar.aspx");
        }
    });
});
